// merchant/merchants/myCardCoupon/index.js
var wxpay = require('../../utils/pay.js');
const utils = require('../../../utils/util.js');
const sharePost = require('../../../utils/sharePost.js');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    CurrentPage: 1,
    loadingMoreHidden: true,
    orderPage: 1,
    loadingMoreHiddenOrder: 1,
    tagindex: 5, //1消费卡、2优惠券、3共享股东、4我的订单、5玖玖卡、6福鲤卡
    tagList: [],
    animationData: "",
    showModalStatus: false,
    animationDataSend: "",
    showModalStatusSend: false,
    userInfo: {},
    cardInfo: {},
    staffUid: 0,
    couponList: [],
    allCardList: [],
    cardId: 0,
    latitude: 0,
    longitude: 0,
    showDialog: false,
    qrCode: '',
    projectname: '',
    timer: '',
    checkResult: {},
    packageInfo: {},
    packageCount: 0,
    sendCount: 0,
    checkCount: 0,
    shareimgpath: '', // 分享小图临时路径
    isHolder: false, //是否为股东
    shareName: '',
    top: 50,
    isSelf: false, //是否自己的名片
    orderState: 1, //1全部2外卖配送3代金券/套餐4退款售后
    orderList: [],
    bossname: '',
    cateIds: '',
    showExtend: 1,
    showSend: false,
    oid: 0,
    createuid: 0,
    showmenu: false,
    msgLength: 0,
    hasJiuCard: false,
    jiuCardCid: 0,
    fuliCardCid: 0,
    showWxcard: false,
    isPlatform: 0,//是否平台的导航我的:0非平台，1平台
    cardItemInfo: {},
    keyword: '',
    merList: [],
    requestNumber: 0,
    myCardId: 0,
    navBarHeight: 44,
    isBuyJJKPack: false,
    cardItemIdJJK: 0,
    lastJJK: 0,
    useJJK: 0,
    showpost: false,//领取玖玖卡海报
    tagindexTY: 1,//1优惠商家2团油
    myCompany: '',
    loginCode: '',
    windowWidth: 340,
    canvasHeight: 490,
    isReceiveWxcard: '',
    canIUseGetUserProfile: false,
    showMeituan: false,
    meituanUrl: '',
    mtPath: ''//美团优惠券领取路径
  },

  // 优惠商家、团油
  changeTagindex: function (e) {
    let tagindexTY = e.currentTarget.dataset.index;
    if (tagindexTY == 2) {//团油
      this.toRefuel();
    }
    this.setData({
      tagindexTY: tagindexTY
    })
  },
  getMobile: function (e) {
    let that = this;
    utils.getMobile(e, function (mobiles) {
      if (mobiles) {
        that.toRefuel();
      } else {
        wx.showToast({
          title: '请授权手机号',
          mask: true
        })
      }
    });
  },
  getUserInfoAgain: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/User/GetUserInfo?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          var realUserInfo = res.data.Data.UserInfo
          app.globalData.userInfo = realUserInfo
          realUserInfo.isAuthor = true;
          if (realUserInfo.Avatar.indexOf("userdefault") != -1) {
            realUserInfo.isAuthor = false;
          }
          that.setData({
            userInfo: realUserInfo
          })
        }
      }
    })
  },

  // 跳转团油
  toRefuel: function () {
    // let platformType = '';
    // let authCode = '';
    // wx.request({
    //   url: app.globalData.host + '/api/Petrol/GetAuthCode?uid=' + app.globalData.userInfo.Uid,
    //   success: function (res) {
    //     if (res.data.Code == 0) {
    //       platformType = res.data.Data.ChannelId;
    //       authCode = res.data.Data.Code;
    //       wx.navigateTo({
    //         url: 'plugin://ty-plugin/index?platformType=' + platformType + '&authCode=' + authCode,
    //       })
    //     } else {
    //       utils.showModal(res.data.Message);
    //     }
    //   }
    // })
  },

  // 促销详情
  toCuxiaoDetail: function (e) {
    let cardId = e.currentTarget.dataset.cardid;
    wx.navigateTo({
      url: '/pages/promotionDetail/index?cardId=' + cardId,
    })
  },
  // 收益
  inMoney: function () {
    wx.navigateTo({
      url: '/fenxiao/profits/index',
    })
  },
  toCardDetailPalt: function (e) {
    let id = e.currentTarget.dataset.id;
    wx.reLaunch({
      url: '/pages/home/index?id=' + id + '&isPlatform=1',
    })
  },
  toMyJJK: function () {
    wx.reLaunch({
      url: '/pages/index/index?id=' + this.data.myCardId + '&isPlatform=1',
    })
  },

  // 授权登陆
  toLogin: function () {
    let back = '/merchant/merchants/myCardCoupon/index';
    wx.redirectTo({
      url: '/pages/accredit/index?back=' + back + '&isPlatform=' + this.data.isPlatform,
    })
  },

  // 购买玖玖卡
  toJiuProdetail: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/product/GetCardProduct?cardType=4',
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.length > 0) {
            let jjkList = res.data.Data;
            let pid = jjkList[0].Pid;
            wx.request({
              url: app.globalData.host + '/api/Store/Product?pid=' + pid + '&isExtend=1',
              success: function (res2) {
                if (res2.data.Code == 0) {
                  var p = res2.data.Data;
                  var seltoid = 0;
                  if (p.Extend && p.Extend.AddUid > 0) {
                    seltoid = p.Extend.AddUid;
                  }
                  wx.navigateTo({
                    url: '/pages/productDetails/index?pid=' + pid + '&cardType=4&seltoid=' + seltoid + '&saleUid=' + that.data.staffUid,
                  })
                }
              }
            })

          }
        } else {
          utils.showModal(res.data.Message);        
        }
      }
    })
  },

  handleInput: function (e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  handleConfirm: function () {
    this.setData({
      CurrentPage: 1,
      merList: []
    })
    this.getMerList(this.data.cardItemInfo.CardItemId);
  },

  handleBlur: function () {
    this.setData({
      CurrentPage: 1,
      merList: []
    })
    this.getMerList(this.data.cardItemInfo.CardItemId);
  },
  handleSearchWord: function () {
    this.setData({
      CurrentPage: 1,
      merList: []
    })
    this.getMerList(this.data.cardItemInfo.CardItemId);
  },


  // 转赠好友
  toSendFriend: function (e) {
    let oid = e.currentTarget.dataset.oid;
    let createuid = e.currentTarget.dataset.createuid;
    this.data.oid = oid;
    this.setData({
      showSend: !this.data.showSend,
      createuid: createuid
    })
  },

  sureSend: function () {
    wx.navigateTo({
      url: '/order/order/giveFriend/index?oid=' + this.data.oid + '&uid=' + app.globalData.userInfo.Uid + '&createuid=' + this.data.createuid,
    })
    this.setData({
      showSend: !this.data.showSend
    })
  },

  closeSend: function () {
    this.setData({
      showSend: !this.data.showSend
    })
  },

  // 查看券码
  toCode: function (e) {
    let oid = e.currentTarget.dataset.oid;
    let name = e.currentTarget.dataset.name;
    let expiretime = e.currentTarget.dataset.expiretime;
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    if (coupontypeid > 0) {
      utils.showModal('请打开微信扫一扫，扫商家收款码，支付时会自动核销代金券！');   
    } else {
      wx.navigateTo({
        url: '/order/order/code/index?oid=' + oid + '&name=' + name + '&expiretime=' + expiretime + '&type=2',
      })
    }
  },

  // 查看券码（外卖订单）
  toCodeFood: function (e) {
    let oid = e.currentTarget.dataset.oid;
    wx.navigateTo({
      url: '/order/order/code/index?oid=' + oid + '&type=1',
    })
  },

  // 代金券/套餐详情
  toOrderDetailCoupon: function (e) {
    let oid = e.currentTarget.dataset.oid;
    let uid = e.currentTarget.dataset.uid;
    let expiretime = e.currentTarget.dataset.expiretime;
    let broprice = e.currentTarget.dataset.broprice;//佣金
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    wx.navigateTo({
      url: '/order/order/orderDetailCoupon/index?oid=' + oid + '&uid=' + uid + '&isBoss=0&expiretime=' + expiretime + '&broprice=' + broprice + '&coupontypeid=' + coupontypeid,
    })
  },

  // 订单状态切换查询
  changeOrderState: function (e) {
    let state = e.currentTarget.dataset.state;
    this.data.cateIds = '';
    this.data.showExtend = 1;
    this.setData({
      orderState: state,
      orderPage: 1
    })
    if (state == 1) {
      this.getOrderList(0);
    }
    if (state == 2) {
      this.data.cateIds = 195;
      this.data.showExtend = 0;
      this.getOrderList(0);
    }
    if (state == 3) {
      this.data.cateIds = '375,376,377,378';
      this.data.orderList = [];
      this.getOrderList(0);
    }
    if (state == 4) {
      this.getOrderList(180);
    }
  },

  // 订单列表
  getOrderList: function (state) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/order/GetUserOrders?uid=' + app.globalData.userInfo.Uid + '&orderState=' + state + '&page=' + that.data.orderPage + '&cateIds=' + that.data.cateIds + '&showExtend=' + that.data.showExtend,
      success: function (res) {
        if (res.data.Code == 0) {
          let orderList = res.data.Data.OrderList;
          let extendList = res.data.Data.ExtendList;
          let productDetailList = res.data.Data.ProductDetailList;
          let printList = res.data.Data.PrintList;
          let staffList = res.data.Data.StaffList;
          let diningTableList = res.data.Data.DiningTableList;
          if (that.data.orderPage != 1) {
            var preGoods = that.data.orderList;
            orderList = preGoods.concat(orderList);
          }
          for (let i = 0; i < orderList.length; i++) {
            orderList[i].expireTime = '';
            orderList[i].shadowPrice = '';
            orderList[i].printNo = 0;
            orderList[i].company = '';
            orderList[i].avater = '';
            orderList[i].BrokeragePrice = 0;
            orderList[i].sid = orderList[i].Sid.trim();
            let proInfoList = orderList[i].ProductInfos;
            for (let h = 0; h < proInfoList.length; h++) {
              if (proInfoList[h].ShowImg.indexOf('ps') != -1) {
                proInfoList[h].ShowImg = utils.formatAvaterByProHead(proInfoList[h].ShowImg);
              } else {
                proInfoList[h].ShowImg = utils.formatAvater(proInfoList[h].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
              }
            }
            if (extendList && extendList.length > 0) {
              for (let j = 0; j < extendList.length; j++) {
                if (orderList[i].ProductInfos[0].Pid == extendList[j].Pid) {
                  orderList[i].expireTime = extendList[j].UseEndTime.substr(0, 10);
                  orderList[i].BrokeragePrice = extendList[j].BrokeragePrice;
                  orderList[i].CouponTypeId = extendList[j].CouponTypeId;
                  break;
                }
              }
            }
            if (productDetailList && productDetailList.length > 0) {
              for (let n = 0; n < productDetailList.length; n++) {
                if (orderList[i].ProductInfos[0].Pid == productDetailList[n].Pid) {
                  orderList[i].shadowPrice = productDetailList[n].ShadowPrice;
                  break;
                }
              }
            }
            if (printList && printList.length > 0) {
              for (let m = 0; m < printList.length; m++) {
                if (orderList[i].Oid == printList[m].Oid) {
                  orderList[i].printNo = printList[m].PrintNo;
                  break;
                }
              }
            }
            if (staffList && staffList.length > 0) {
              for (let r = 0; r < staffList.length; r++) {
                if (staffList[r].Uid == orderList[i].ProductInfos[0].CreateUid) {
                  orderList[i].staffid = staffList[r].Id;
                  orderList[i].company = staffList[r].Company;
                  orderList[i].avater = utils.formatAvater(staffList[r].Avater, 'https://static.711688.net.cn/upload/card/source/');
                }
              }
            }
            if (diningTableList && diningTableList.length > 0) {
              for (let k = 0; k < diningTableList.length; k++) {
                if (diningTableList[k].Id == orderList[i].Sid.trim()) {
                  orderList[i].tableNumber = diningTableList[k].TableNumber;
                  orderList[i].tableName = diningTableList[k].Name;
                }
              }
            }
            orderList[i].Jump=0;
            if(proInfoList[0].CateId ==377 || proInfoList[0].CateId==378){
              orderList[i].Jump = 11;
            }
          }
          
          that.setData({
            orderList: orderList,
            loadingMoreHiddenOrder: res.data.Data.PageModel.TotalPages
          })
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  // 订单详情
  toOrderDetail: function (e) {
    let oid = e.currentTarget.dataset.oid;
    let uid = e.currentTarget.dataset.uid;
    wx.navigateTo({
      url: '/order/order/orderDetail/index?oid=' + oid + '&uid=' + uid + '&isBoss=0',
    })
  },

  // 退款
  tuikuan: function (e) {
    let oid = e.currentTarget.dataset.oid;
    let money = e.currentTarget.dataset.money;
    wx.navigateTo({
      url: '/order/order/tuikuan/index?oid=' + oid + '&money=' + money,
    })
  },
  // 马上付款
  toPayTap: function (e) {
    var oid = e.currentTarget.dataset.id;
    let broPrice = e.currentTarget.dataset.brokerageprice;
    let url = '/merchant/merchants/myCardCoupon/index?tagindex=4';
    if (broPrice > 0) {//带佣金的产品
      wxpay.wxpay(app, oid, 2, url);
    } else {
      wxpay.wxpayWm(app, oid, url);
    }
  },
  // 取消订单
  cancelOrderTap: function (e) {
    var that = this;
    var orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '取消中',
            mask: true
          })
          wx.request({
            url: app.globalData.host + '/api/order/CancelOrder',
            data: {
              uid: app.globalData.userInfo.Uid,
              oid: orderId
            },
            success: (res) => {
              wx.hideLoading();
              if (res.data.Code == 0) {
                that.getOrderList(0);
              } else {
                utils.showModal(res.data.Message);               
              }
            }
          })
        }
      }
    })
  },
  // 确认收货
  receiveOrder: function (e) {
    let that = this;
    let oid = e.currentTarget.dataset.oid;
    wx.showModal({
      title: '提示',
      content: '是否确认收货?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Order/ReceiveOrder?uid=' + app.globalData.userInfo.Uid + '&oid=' + oid,
            success: function (res) {
              if (res.data.Code == 0) {
                wx.showToast({
                  mask: true,
                  title: '订单已完成',
                  duration: 500
                })
                that.getOrderList(0);
              } else {
                utils.showModal(res.data.Message);
              }
            }
          })
        }
      }
    })
  },
  //再来一单
  buyAgain: function (e) {
    let that = this;
    let productList = e.currentTarget.dataset.info;
    that.data.bossname = e.currentTarget.dataset.bossname;   
    that.clearCart(productList[0].CreateUid, function (flag) {
      if (flag) { //清空购物车完成      
        that.addShopCar(productList, 0);
      }
    })
  },
  // 再来一单（代金券/套餐）
  buyAgainCoupon: function (e) {
    let that = this;
    var productList= [];
    productList.push({
      Uid: app.globalData.userInfo.Uid,
      Pid: e.currentTarget.dataset.pid,
      RealCount: e.currentTarget.dataset.buycount,      
      CreateUid: e.currentTarget.dataset.createuid,
      OptionIds: ''
    });
    that.clearCart(productList[0].CreateUid, function (flag) {
      if (flag) { //清空购物车完成      
        that.addShopCar(productList, 1);
      }
    })
  },

  // 转为unicode 编码
  encodeUnicode: function (str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
      res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
  },

  // 清空购物车
  clearCart: function (createuid, cb) {
    wx.request({
      url: app.globalData.host + '/api/Cart/Clear?uid=' + app.globalData.userInfo.Uid + '&createUid=' + createuid,
      success: function (res) {
        cb(res.data.Data);
      }
    })
  },

  // 加入购物车（单品/套餐/优惠券）
  addShopCar: function (productList,isCoupon) {
    var that = this;
    for(var i = 0;i < productList.length; i++){
      var p = productList[i]; 
      var index = i;
      wx.request({
        url: app.globalData.host + '/api/cart/AddProduct',
        data: {
          uid: p.Uid,
          pid: p.Pid,
          buyCount: p.RealCount,
          optionIds: p.OptionIds,
          createUid: p.CreateUid
        },
        success: function (res) {
          if (res.data.Code == 0) {
            if(index == productList.length - 1){
              if(isCoupon == 1){
                wx.navigateTo({   // 跳转优惠券购物车页面
                  url: '/order/order/cart/index?isCoupon=1&stockNumber=' + p.StockNumber + '&seltoid=' + p.CreateUid,
                })
              }else{              
                wx.navigateTo({   //单品加购
                  url: '/order/order/cart/index?isCoupon=0&bossname=' + that.data.bossname + '&seltoid=' + p.CreateUid,
                })
              }           
            }            
          } else {
            utils.showModal(res.data.Message);
          }
        }
      })
    }    
  },
  // 加载更多(我的订单)
  loadMoreOrder: function () {
    var that = this;
    var currPage = that.data.orderPage;
    let orderState = that.data.orderState;
    var state = 0;
    if (orderState == 4) {
      state = 180;
    }
    that.setData({
      orderPage: currPage + 1
    })
    that.getOrderList(state);
  },
  // 加载更多(玖玖卡商家)
  loadMoreStaff: function () {
    let that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.CurrentPage < that.data.loadingMoreHidden) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      that.getMerList(that.data.cardItemInfo.CardItemId);
    } else {
      return
    }
  },
  onReachBottom: function () {
    if (this.data.tagindex > 4) {
      this.loadMoreStaff();
    }
  },

  // 获取地理位置  
  getLocation: function () {
    let that = this;
    utils.getLocation((location)=>{
      that.data.latitude = location.lat;
      that.data.longitude = location.lng;
      if (that.data.isPlatform == 1) { 
        that.getAllCardItems();  //平台
      } else {
        that.getAiCardInfo();
      }
    },app);   
  },
  
  openMap: function (e) {
    let latitude = e.currentTarget.dataset.latitude;
    let longitude = e.currentTarget.dataset.longitude;
    let company = e.currentTarget.dataset.company;
    wx.showModal({
      title: '提示',
      content: '是否打开地图导航',
      success: function (res) {
        if (res.confirm) {
          wx.openLocation({
            latitude: latitude,
            longitude: longitude,
            scale: 28,
            name: "点击右边打开地图导航",
            address: company
          })
        }
      }
    })
  },

  //优惠券核销码
  toWrCode: function (e) {
    let orderamountlower = e.currentTarget.dataset.orderamountlower;
    let name = e.currentTarget.dataset.name;
    let money = e.currentTarget.dataset.money;
    let couponid = e.currentTarget.dataset.couponid;
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    let extcode1 = e.currentTarget.dataset.extcode1;
    let extcode2 = e.currentTarget.dataset.extcode2;
    let wxcoupontypeid = e.currentTarget.dataset.wxcoupontypeid;
    let distance = e.currentTarget.dataset.distance;
    if (wxcoupontypeid != 0) {
      utils.showModal('请打开微信扫一扫，扫商家收款码，支付时会自动核销代金券！');     
    } else {
      // 是否美团券（测试）
      let that = this;
      wx.request({
        // url: app.globalData.host + '/api/meituan/getunionUrl?uid=' + app.globalData.userInfo.Uid + '&coupontypeid=' + 17028,
        url: app.globalData.host + '/api/meituan/getunionUrl?uid=' + app.globalData.userInfo.Uid + '&coupontypeid=' + coupontypeid,
        success: function (res) {
          console.log(res)
          if (res.data.Data.url) {
            console.log('美团券===');
            that.data.mtPath = res.data.Data.path;
            that.setData({
              meituanUrl: res.data.Data.url,
              showMeituan: true
            })
          } else {
            wx.navigateTo({
              url: '/merchant/merchants/qrCode/index?money=' + money + "&orderamountlower=" + orderamountlower + "&couponid=" + couponid + "&name=" + name + "&extcode1=" + extcode1 + "&extcode2=" + extcode2 + '&distance=' + distance,
            })
          }
        }
      })
    }
  },
  // 领取美团券
  receiveMeituan: function () {
    wx.navigateToMiniProgram({
      appId: 'wxde8ac0a21135c07d',
      path: this.data.mtPath
    })
    //  wx.navigateToMiniProgram({
    //   appId: 'wxde8ac0a21135c07d',
    //   path: 'mp://sQg4cqJK7eV5Bku'
    // })
  },

  closeMeituan: function () {
    this.setData({
      showMeituan: false
    })
  },

  // 优惠券、会员卡详情
  toDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let couponid = e.currentTarget.dataset.couponid;
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    let createUid = e.currentTarget.dataset.createuid;
    let shareUid = e.currentTarget.dataset.shareuid;
    let staffid = e.currentTarget.dataset.staffid;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&couponid=' + couponid + '&createUid=' + createUid + '&shareUid=' + shareUid + '&coupontypeid=' + coupontypeid + '&staffid=' + staffid,
    })
  },

  // 优惠券详情
  toCouponDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let couponid = e.currentTarget.dataset.couponid;
    let coupontypeid = e.currentTarget.dataset.coupontypeid; //股东礼包查看详情需要
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&couponid=' + couponid + '&coupontypeid=' + coupontypeid,
    })
  },

  // 消费卡详情
  toCardItemDetail: function (e) {
    let id = e.currentTarget.dataset.id;
    let type = e.currentTarget.dataset.type;
    let cid = e.currentTarget.dataset.cid;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&cid=' + cid + '&ids=' + id,
    })
  },

  // 查看积分
  toJifen: function (e) {
    let staffuid = e.currentTarget.dataset.staffuid;
    wx.navigateTo({
      url: '../recordsByUser/index?jifen=1&uid=' + staffuid + '&user=true',
    })
  },

  //查看名片
  tocardDetails: function (e) {
    let cardId = e.currentTarget.dataset.id;
    wx.reLaunch({
      url: '/pages/home/index?id=' + cardId,
    })
  },

  // 会员查看消费卡消费记录
  toRecores: function (e) {
    let uid = e.currentTarget.dataset.uid;
    let cid = e.currentTarget.dataset.cid;
    wx.navigateTo({
      url: '../recordsByUser/index?uid=' + uid + '&cid=' + cid + '&jifen=0',
    })
  },

  getUserProfile: function () {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('用于完善会员资料', res);
        utils.AuthorizeUserInfo(res, that.data.loginCode, function (flag) {
          if (flag) {
            wx.showToast({
              title: '授权成功',
              icon: 'none'
            })
            that.getUserInfoAgain();
          } else {//注册失败，重新点击授权
            wx.login({
              success: function (res) {
                that.data.loginCode = res.code;
              }
            })
          }
        });
      },
      fail: (err) => {
        wx.showToast({
          title: '用户拒绝授权',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.hideShareMenu(); //隐藏右上角转发按钮；
    that.setData({
      navBarHeight: app.globalData.navBarHeight
    })
    if (wx.getUserProfile) {
      that.setData({
        canIUseGetUserProfile: true
      })
    }
    wx.login({
      success: (res) => {
        that.setData({
          loginCode: res.code
        })
      },
    })
    if (options.isPlatform && options.isPlatform == 1) {
      that.setData({
        isPlatform: options.isPlatform
      })
    }

    let showIndex = wx.getStorageSync('showIndex');
    if (showIndex == '/merchant/merchants/myCardCoupon/index') {
      that.setData({
        showmenu: true
      })
    }
    if (options.staffId) {
      wx.setStorageSync("cardId", options.staffId);
    }

    if (options.tagindex) {
      if (options.showWxcard && options.showWxcard == 1) {//弹出弹窗：是否领取到微信卡包
        that.setData({
          showWxcard: true
        })
      }
      that.setData({
        tagindex: options.tagindex
      }) 
    }
   
    if (options.fromwxcard && options.fromwxcard == 1) {//从微信卡包跳转过来的
      return;
    } else {  
       that.getLocation();  
    }
        
    var windowWidth = wx.getSystemInfoSync().windowWidth * 0.9;
    var canvasHeight = windowWidth * 1.33;
    this.setData({
      windowWidth: windowWidth,
      canvasHeight: canvasHeight
    })
  },

  closeWxcard: function () {
    this.setData({
      showWxcard: false
    })
  },

  sureWxcard: function (e) {
    let that = this;
    if (e.detail.iv) {
      wx.login({
        success: function (ress) {
          // 下面开始调用注册接口
          wx.request({
            url: app.globalData.host + '/api/account/WxOpenRegister',
            data: {
              code: ress.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              storeid: app.globalData.storeId,
              storeAppId: app.globalData.storeAppId
            }, // 设置请求的 参数
            method: 'POST',
            success: (res) => {

            }
          })
        }
      })
    }
    that.sureWxcardConfirm();
  },

  getMobiles: function (e) {
    let that = this;
    utils.getMobile(e, function (mobiles) {
      that.sureWxcardConfirm();
    })
  },

  // 领取到卡包
  sureWxcardConfirm: function () {
    let that = this;
    let cardId = 'pm_m_1G_c5QN9idL-IxgeraE3Do8';
    wx.request({
      url: app.globalData.host + '/api/wxCard/getcardsign?card_id=' + cardId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.closeWxcard();
          if (res.data.Data) {
            let info = res.data.Data;
            let timestamp = info.timestamp;
            let signature = info.signature;
            let noncestr = info.nonce_str;
            wx.addCard({
              cardList: [
                {
                  cardId: cardId,
                  cardExt: '{"timestamp":"' + timestamp + '","signature":"' + signature + '","nonce_str":"' + noncestr + '"}'
                }],
              success(res2) {
                let codeSTR = res2.cardList[0].code;
                that.addWxCardList(cardId, codeSTR);
              },
              fail(err) {
                console.log(err)
              }
            })
          }
        } else {
          utils.showModal(res.data.Message);          
        }

      }
    })
  },

  // 领到微信卡包后调用
  addWxCardList: function (cardid, code) {
    wx.request({
      url: app.globalData.host + '/api/wxcard/ReceiveCard?uid=' + app.globalData.userInfo.Uid + '&card_id=' + cardid + '&code=' + encodeURIComponent(code),
      success: function (res) {

      },
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    that.hideModal();
    if (app.globalData.userInfo) {
      wx.request({
        url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + app.globalData.userInfo.Uid,
        success: function (res) {
          if (res.data.Code == 0) {
            if (res.data.Data) {
              let staffid = res.data.Data.Id;
              that.data.myCompany = res.data.Data.Company;
              that.setData({
                myCardId: staffid
              })
            }
          }
        },
      })
      let userInfo = app.globalData.userInfo;
      userInfo.isAuthor = true;
      if (userInfo.Avatar.indexOf("userdefault") != -1) {//未授权
        wx.request({
          url: app.globalData.host + '/api/User/GetUserInfo?uid=' + app.globalData.userInfo.Uid,
          success: function (res) {
            if (res.data.Code == 0) {
              let lastAvatar = res.data.Data.UserInfo.Avatar;
              userInfo.Avatar = lastAvatar;
              userInfo.NickName = res.data.Data.UserInfo.NickName;
              if (lastAvatar.indexOf("userdefault") != -1) {
                userInfo.isAuthor = false;
              }
              app.globalData.userInfo = userInfo;
            }
            that.setData({
              userInfo: userInfo
            })
          }
        })
      } else {
        that.setData({
          userInfo: userInfo
        })
      }
    } else {
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  // 显示二维码(会员卡/右上角客户详情码)
  showQrcode: function (e) {
    let istocusdetail = e.currentTarget.dataset.istocusdetail;
    let cardId = e.currentTarget.dataset.cardid;//玖玖客id
    let id = 0;
    let creatUid = 0;
    let title = '';
    let company = '';
    if (istocusdetail == 0) {//会员卡
      id = e.currentTarget.dataset.id;
      creatUid = e.currentTarget.dataset.creatuid;
      title = e.currentTarget.dataset.cardtitle;
      company = e.currentTarget.dataset.company;
      this.setData({
        currentVipTitle: title,
        currentCompany: company
      })
    }

    this.getClientid(id, creatUid, istocusdetail, cardId);
    this.setData({
      showDialog: !this.data.showDialog,
      projectname: ''
    })
  },

  // 获取会员卡二维码
  getQrcode: function (clientid, id, creatuid, istocusdetail, cardId) {
    var that = this;
    let urlparam = '';
    let path = '';
    if (istocusdetail == 1) { //跳客户详情(已弃用)
      urlparam = 'staffId=' + cardId + '&clientid=' + clientid + '&rand=' + Math.random();
      path = "/pages/h5page/index?url=customerDetail.html&urlparam=" + encodeURIComponent(urlparam);
    }
    if (istocusdetail == 0) { //折扣卡核销
      path = 'merchant/share/toVerifications/index?t=5&p=' + creatuid + '#' + app.globalData.userInfo.Uid + '#' + id + '#' + cardId;
    }
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: path,
        storeappid: app.globalData.storeAppId,
        type: "coupon"
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              qrCode: 'https://static.711688.net.cn/upload/couponcode/' + res.data.Data
            })
          }
        } else {
          utils.showModal(res.data.Message);
        }
      },
    })
  },

  // 关闭二维码弹窗（消费卡+会员卡）
  closeQrcode: function () {
    this.setData({
      showDialog: false,
      qrCode: ''
    })
    clearInterval(this.data.timer);
  },

  // 消费卡核销码
  showQrcodeCardItem: function (e) {
    let cid = e.currentTarget.dataset.cid;
    let cardType = e.currentTarget.dataset.cardtype;
    let projectname = e.currentTarget.dataset.name;
    let company = e.currentTarget.dataset.company;
    let cardId = e.currentTarget.dataset.cardid;
    this.getQrcodeByCardItem(cid, cardType, cardId);
    this.setData({
      showDialog: !this.data.showDialog,
      projectname: projectname,
      currentCompany: company,
      checkResult: {}
    })
  },

  // 刷新小程序码状态
  freshCode: function (cid, lastTime) {
    let that = this;
    var timesRun = 0;
    var timer = setInterval(function () {
      timesRun += 1;
      if (timesRun === 30) {
        clearInterval(timer);
      }
      wx.request({
        url: app.globalData.host + '/api/Coupon/IsCheckCard',
        data: {
          cid: cid,
          lastTime: lastTime
        },
        month: 'POST',
        success: function (res) {
          if (res.data.Code == 0) {
            if (res.data.Data != null) {
              let checkResult = res.data.Data;
              checkResult.oldExpireTime = utils.formatTime(utils.jianDate(checkResult.ExpireTime, checkResult.Amount));
              checkResult.oldExpireTime = checkResult.oldExpireTime.substr(0, 10).replace(/\//g, "-");
              that.setData({
                checkResult: checkResult
              })
              clearInterval(timer);
            }
          } else {
            utils.showModal(res.data.Message);
          }
        }
      })
    }, 3000)
    that.data.timer = timer;
  },

  //  客户id
  getClientid: function (id, creatuid, istocusdetail, cardId) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/AddressBook/GetClientInfo',
      data: {
        uid: app.globalData.userInfo.Uid,
        staffId: cardId
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.getQrcode(res.data.Data.Id, id, creatuid, istocusdetail, cardId);
        }
      }
    })
  },

  // 获取消费卡二维码
  getQrcodeByCardItem: function (cid, cardType, cardId) {
    var that = this;
    // let cardId = wx.getStorageSync('cardId');
    let activetype = 2;
    if (cardType == 3) {
      activetype = 1;
    }
    // path: "/merchant/share/sendOrcheckProject/index?cid=" + cid + '&cardtype=' + cardType + '&clientuid=' + app.globalData.userInfo.Uid + '&cardid=' + cardId + '&activetype=' + activetype,
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: "merchant/share/sendOrcheckProject/index?t=6&p=" + cid + '#' + cardType + '#' + app.globalData.userInfo.Uid + '#' + cardId + '#' + activetype,
        storeappid: app.globalData.storeAppId,
        type: "coupon"
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              qrCode: 'https://static.711688.net.cn/upload/couponcode/' + res.data.Data
            })
          }
        }
        that.freshCode(cid, res.data.ServerTime);
      },
    })
  },

  // 获取名片信息
  getAiCardInfo: function () {
    var that = this;
    var cardId = wx.getStorageSync("cardId");
    if (!cardId) {
      cardId = that.data.cardId;
    }
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/GetAiCardDetail?uid=' + app.globalData.userInfo.Uid + '&staffId=' + cardId,
      success: function (res) {
        if (res.data.Code == 0) {
          let cardInfo = res.data.Data;
          let staffUid = cardInfo.CardInfo.Uid;
          let isSelf = false;
          if (app.globalData.userInfo.Uid == staffUid) { //查看自己名片
            isSelf = true;
          }

          that.setTagList([],that.data.tagindex);
          that.getTabData(that.data.tagindex);
          // that.getAllCardItems();
          that.getShareholder(staffUid);
          that.getShareholderByUserid();
          that.isTipUser(staffUid);
          utils.getMsgUnRead(staffUid, function (msgLength) {
            that.setData({
              msgLength: msgLength
            })
          })
          cardInfo.CardInfo.Avater = utils.formatAvater(cardInfo.CardInfo.Avater, 'https://static.711688.net.cn/upload/card/source/');
          that.setData({
            cardInfo: cardInfo,
            isSelf: isSelf
          })
          that.data.staffUid = staffUid;
        } else {
          wx.showToast({
            title: '玖玖客加载失败',
            duration: 2000,
            mask: true
          })
          setTimeout(function () {
            wx.redirectTo({url: '/pages/weijieke/cardList/index'})
          }, 2000)
        }
      }
    })
  },

  //消费卡、优惠券、共享股东、我的订单切换
  changeTag: function (e) {
    let that = this;
    let tagindex = e.currentTarget.dataset.tagindex;
    that.setData({
      CurrentPage: 1,
      tagindex: tagindex,
      orderState: 1
    })
    that.getTabData(tagindex);
    // if (tagindex == 1) {
    //   that.getAllCardItems();
    // }
    // if (tagindex == 2) {
    //   that.getAllCoupon();
    // }
    // if (tagindex == 3) {
    //   that.getPackageTotal(that.data.staffUid);
    //   that.getPackageInfo(that.data.staffUid);
    // }
    // if (tagindex == 4) {
    //   that.getOrderList(0);
    // }
    // if (tagindex == 5) {
    //   that.getJiuCardDetail(that.data.jiuCardCid);
    // }
    // if (tagindex == 6) {
    //   that.getJiuCardDetail(that.data.fuliCardCid);
    // }
  },
  //获取tab页数据
  getTabData: function(tagindex){
    let that = this;
    console.log('tagindex',tagindex)
    console.log('jiuCardCid',that.data.jiuCardCid)
    if (tagindex == 1) {
      that.getAllCardItems();
    }
    if (tagindex == 2) {
      that.getAllCoupon();
    }
    if (tagindex == 3) {
      that.getPackageTotal(that.data.staffUid);
      that.getPackageInfo(that.data.staffUid);
    }
    if (tagindex == 4) {
      that.getOrderList(0);
    }
    if (tagindex == 5) {
      if(that.data.jiuCardCid<=0){
        that.getAllCardItems();
      }else{
        that.getJiuCardDetail(that.data.jiuCardCid);
      }      
    }
    if (tagindex == 6) {
      that.getJiuCardDetail(that.data.fuliCardCid);
    }
  },
   //设置tab导航
  setTagList: function(appendList = [],tagindex = 4){
    let tagList = [
      { id: 1, type: '消费卡', url: '/images/my/costcard.png' }, 
      { id: 2, type: '优惠券', url: '/images/my/coupon.png' },
      { id: 4, type: '我的订单', url: '/images/my/order.png' },
    ];
    for(var i = 0 ;i < appendList.length; i++){
      tabList.push(appendList[i]);
    }
    this.setData({
      showTag: true,
      tagList: tagList,
      tagindex: tagindex
    })
  },
  // 获取所有的消费卡+会员折扣卡
  getAllCardItems: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardListByDistance?uid=' + app.globalData.userInfo.Uid + '&page=' + that.data.CurrentPage + '&longitude=' + that.data.longitude + '&latitude=' + that.data.latitude,
      success: function (res) {
        that.data.requestNumber += 1;
        let allCardList = res.data.Data.Items;
        if (that.data.CurrentPage != 1) {
          var preGoods = that.data.allCardList;
          allCardList = preGoods.concat(allCardList);
        }
        let tagList = [{ id: 1, type: '消费卡', url: '/images/my/costcard.png' }, { id: 2, type: '优惠券', url: '/images/my/coupon.png' }, { id: 4, type: '我的订单', url: '/images/my/order.png' }];
        let jiuCardCid = 0;
        let fuliCardCid = 0;
        let tagindex = 1;
        let isReceiveWxcard = '';
        if (allCardList && allCardList.length > 0) {
          for (let i = 0; i < allCardList.length; i++) {
            allCardList[i].Avater = utils.formatAvater(allCardList[i].Avater, 'https://static.711688.net.cn/upload/card/source/');
            allCardList[i].Distances = parseFloat(allCardList[i].Distance / 1000).toFixed(2);

            if (allCardList[i].Card) {
              allCardList[i].Card.EndTime = allCardList[i].Card.EndTime.substr(0, 10).replace(/-/g, "/");
              allCardList[i].Card.Discount = allCardList[i].Card.Discount * 0.1;
              allCardList[i].Card.Discount = allCardList[i].Card.Discount.toFixed(1);
              allCardList[i].Card.CardNo = allCardList[i].Card.CardNo.replace(/\s/g, '').replace(/(.{4})/g, "$1 ");
            }
            if (allCardList[i].CardItemList.length > 0) {

              let carditems = allCardList[i].CardItemList;
              for (let j = 0; j < carditems.length; j++) {
                if (carditems[j].CardType == 4) {
                  jiuCardCid = carditems[j].Cid;
                  isReceiveWxcard = carditems[j].WxCode;
                }
                if (carditems[j].CardType == 5) {//福鲤卡
                  fuliCardCid = carditems[j].Cid;
                }
                carditems[j].ExpireTime = carditems[j].ExpireTime.substr(0, 10);
                carditems[j].Logo = utils.formatAvater(carditems[j].Logo, 'https://static.711688.net.cn/upload/card/source/');
                var detailpics = carditems[j].DetailPics;
                carditems[j].showDetailPics = '';
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  carditems[j].showDetailPics = list[0];
                }
              }
              allCardList[i].CardItemList = carditems;
            }
          }
          if (jiuCardCid > 0) {
            tagindex = 5;
            that.getJiuCardDetail(jiuCardCid);
            if (fuliCardCid > 0) {
              tagList = [{ id: 5, type: '玖玖卡', url: '/images/my/jiucard.png' }, { id: 6, type: '福鲤卡', url: '/images/my/fulicard.png' }, { id: 1, type: '消费卡', url: '/images/my/costcard.png' }, { id: 2, type: '优惠券', url: '/images/my/coupon.png' }, { id: 4, type: '我的订单', url: '/images/my/order.png' }];
            } else {
              tagList = [{ id: 5, type: '玖玖卡', url: '/images/my/jiucard.png' }, { id: 1, type: '消费卡', url: '/images/my/costcard.png' }, { id: 2, type: '优惠券', url: '/images/my/coupon.png' }, { id: 4, type: '我的订单', url: '/images/my/order.png' }];
            }
          }
          if (jiuCardCid == 0 && fuliCardCid > 0) {
            tagindex = 6;
            that.getJiuCardDetail(fuliCardCid);
            tagList = [{ id: 6, type: '福鲤卡', url: '/images/my/fulicard.png' }, { id: 1, type: '消费卡', url: '/images/my/costcard.png' }, { id: 2, type: '优惠券', url: '/images/my/coupon.png' }, { id: 4, type: '我的订单', url: '/images/my/order.png' }];
          }
        }
        that.getCardPackage(that.data.requestNumber, tagindex, tagList);//玖玖卡套餐
        that.data.fuliCardCid = fuliCardCid;
        that.setData({
          jiuCardCid: jiuCardCid,
          allCardList: allCardList,
          isReceiveWxcard: isReceiveWxcard,
          loadingMore: res.data.Data.TotalPages
        })
      }
    })
  },

  getJiuCardDetail: function (cid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardUser?cid=' + cid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.getMerList(res.data.Data.CardItemId);
            let cardItemInfo = res.data.Data;
            cardItemInfo.ExpireTime = cardItemInfo.ExpireTime.substr(0, 10);
            that.setData({
              cardItemInfo: cardItemInfo
            })
          }
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  getMerList: function (cardItemId) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/staff/GetListByConfig',
      data: {
        cardItemId: cardItemId,
        storeAppId: app.globalData.storeAppId,
        latitude: that.data.latitude,
        longitude: that.data.longitude,
        keyword: that.data.keyword,
        page: that.data.CurrentPage
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Items.length > 0) {
            let merList = res.data.Data.Items;
            if (that.data.CurrentPage != 1) {
              let preList = that.data.merList;
              merList = preList.concat(merList);
            }
            for (let i = 0; i < merList.length; i++) {
              merList[i].Avater = utils.formatAvater(merList[i].Avater, 'https://static.711688.net.cn/upload/card/source/');
              if (merList[i].Distance >= 1000) {
                merList[i].Distances = parseFloat(merList[i].Distance / 1000).toFixed(2);
              }
              merList[i].ShowDiscount = (100 - merList[i].UseDiscount) / 10;
            }
            that.setData({
              merList: merList,
              loadingMoreHidden: res.data.Data.TotalPages
            })
          }
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  getCardPackage: function (requestNumber, tagindex, tagList) {
    let that = this;
    let isBuy = false;
    wx.request({
      url: app.globalData.host + '/api/coupon/GetCardPack?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.IsBuy) {//已购买299的玖玖卡套餐
            isBuy = res.data.Data.IsBuy;
            let totalBuyCountJJK = res.data.Data.BuyCount;
            let useJJK = res.data.Data.UseCount;
            let lastJJK = parseInt(totalBuyCountJJK - useJJK);
            that.data.cardItemIdJJK = res.data.Data.CardItemId;
            if (tagindex != 5) {
              tagindex = 5;
              that.getJiuCardDetail(res.data.Data.CardItemId);
              let obj = {};
              obj = { id: 5, type: '玖玖卡', url: '/images/my/jiucard.png' };
              tagList.unshift(obj);
            }
            that.setData({
              isBuyJJKPack: isBuy,
              lastJJK: lastJJK,
              useJJK: useJJK
            })
          }
          if (requestNumber == 1) {
            that.setData({
              tagindex: tagindex
            })
          }
          that.setData({
            showTag: true,
            tagList: tagList
          })
        } else {
          utils.showModal(res.data.Message);
        }
      },
    })
  },

  // 获取我领取的所有玖玖客商家的优惠券
  getAllCoupon: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/coupon/GetCouponListByDistance?uid=' + app.globalData.userInfo.Uid + '&longitude=' + that.data.longitude + '&latitude=' + that.data.latitude + '&page=' + that.data.CurrentPage,
      success: function (res) {
        let couponList = res.data.Data.List;
        if (that.data.CurrentPage != 1) {
          var preGoods = that.data.couponList;
          couponList = preGoods.concat(couponList);
        }
        if (couponList.length > 0) {
          for (let i = 0; i < couponList.length; i++) {
            couponList[i].useendtime = couponList[i].useendtime.substr(0, 10);
            couponList[i].Logo = utils.formatAvater(couponList[i].Logo, 'https://static.711688.net.cn/upload/card/source/');
            if (couponList[i].Distance >= 1000) {
              couponList[i].Distances = parseFloat(couponList[i].Distance / 1000).toFixed(2);
            }
            if (couponList[i].name == '') {
              if (couponList[i].money > 0) {//满减券
                couponList[i].name = '满' + couponList[i].orderamountlower + '减' + couponList[i].money + '代金券';
              } else {
                if (couponList[i].extcode2) {//赠品券
                  if (couponList[i].extcode1) {
                    couponList[i].name = '买' + extcode1 + '送' + extcode2;
                  } else {
                    couponList[i].name = '送' + extcode2;
                  }
                }
              }
            }
            var detailpics = couponList[i].DetailPics;
            couponList[i].showDetailPics = '';
            var list = [];
            if (detailpics != '') {
              var newDetailPics = detailpics.split(",");
              for (let k = 0; k < newDetailPics.length; k++) {
                list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
              }
              couponList[i].showDetailPics = list[0];
            }
          }
        }
        that.setData({
          couponList: couponList,
          loadingMore: res.data.Data.PageModel.TotalPages
        })
      }
    })
  },

  // 加载更多（消费卡/优惠券）
  loadMoreCouponOrCard: function () {
    var that = this;
    let tagindex = that.data.tagindex;
    if (that.data.loadingMore > 1 && that.data.CurrentPage < that.data.loadingMore) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      if (tagindex == 1) {
        that.getAllCardItems();
      }
      if (tagindex == 2) {//优惠券
        that.getAllCoupon();
      }
    } else {
      return
    }
  },

  // 获取股东礼包
  getPackageInfo: function (createUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Shareholder/GetPackageInfo?createUid=' + createUid + '&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          let packageInfo = res.data.Data;
          let card = {};
          let cardItemList = [];
          let couponTypeList = [];
          if (packageInfo.card != null) {
            card = packageInfo.card;
            card.EndTime = card.EndTime.substr(0, 10).replace(/-/g, "/");
            card.Discount = (card.Discount * 0.1).toFixed(1);
          }
          if (packageInfo.cardItemList.length > 0) {
            cardItemList = packageInfo.cardItemList;
            for (let i = 0; i < cardItemList.length; i++) {
              cardItemList[i].ExpireTime = utils.formatTime(utils.jiaDate(cardItemList[i].AddTime, cardItemList[i].Days));
              cardItemList[i].ExpireTime = cardItemList[i].ExpireTime.substr(0, 10).replace(/\//g, "-");
              cardItemList[i].AddTime = cardItemList[i].AddTime.substr(0, 10);
              cardItemList[i].showDetailPics = '';
              if (cardItemList[i].DetailPics) {
                var detailpics = cardItemList[i].DetailPics;
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  cardItemList[i].showDetailPics = list[0];
                }
              }
            }
          }
          if (packageInfo.couponTypeList.length > 0) {
            couponTypeList = packageInfo.couponTypeList;
            for (let j = 0; j < couponTypeList.length; j++) {
              couponTypeList[j].usestarttime = couponTypeList[j].usestarttime.substr(0, 10);
              couponTypeList[j].useendtime = couponTypeList[j].useendtime.substr(0, 10);
              couponTypeList[j].showDetailPics = '';
              if (couponTypeList[j].DetailPics) {
                var detailpics = couponTypeList[j].DetailPics;
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  couponTypeList[j].showDetailPics = list[0];
                }
              }
            }
          }
          that.setData({
            packageInfo: packageInfo
          })
          if (that.data.packageInfo.couponTypeList.length > 0) {
            that.getShareImgData(that.data.packageInfo.couponTypeList[0]);
          } else {
            that.getShareImgData2();
          }
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  // 礼包使用统计
  getPackageTotal: function (createUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Shareholder/GetPackageTotal?createUid=' + createUid + '&shareUid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            packageCount: res.data.Data.PackageCount,
            sendCount: res.data.Data.SendCount,
            checkCount: res.data.Data.CheckCount
          })
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  // 一键分享（股东礼包）
  formSubmitCouponShare: function () {
    this.showModal();
  },
  formSubmitJJK: function () {

    if (this.data.lastJJK > 0) {
      this.showModalSend();
    } else {
      utils.showModal('您已经没有可转赠的玖玖卡了，请继续购买再转赠好友');     
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var that = this;
    let type = e.target.dataset.type;
    let path = '';
    that.hideModalSend();
    if (type == 1) {
      var cardInfo = that.data.cardInfo;
      var shareTitle = cardInfo.CardInfo.Company + '的老板' + app.globalData.userInfo.NickName + '给您赠送了红包,点击领取';
      path = '/pages/index/index?holderid=' + app.globalData.userInfo.Uid + '&id=' + cardInfo.CardInfo.Id + '&holderName=' + app.globalData.userInfo.NickName + '&source=4';
      return {
        imageUrl: that.data.shareimgpath ? that.data.shareimgpath : cardInfo.CardInfo.Avater,
        title: shareTitle,
        path: path,
        success: function () {
          that.hideModal();
        }
      }
    } else {
      if (type == 2) {//群
        path = '/merchant/merchants/receiveJJK/index?id=' + that.data.myCardId + '&cardItemId=' + that.data.cardItemIdJJK + '&createUid=' + app.globalData.userInfo.Uid + '&timestamp=' + Date.parse(new Date()) / 1000 + '&source=0';
      } else if (type == 3) {//单个好友
        path = '/merchant/merchants/receiveJJK/index?id=' + that.data.myCardId + '&cardItemId=' + that.data.cardItemIdJJK + '&createUid=' + app.globalData.userInfo.Uid + '&timestamp=' + Date.parse(new Date()) / 1000 + '&source=1';
      }
      return {
        imageUrl: "https://static.711688.net.cn/upload/card/source/ua_2011261010365946827.jpg",
        path: path
      }
    }
  },

  //已发玖玖卡记录
  toSendJJKRecord: function () {
    wx.navigateTo({
      url: '/merchant/merchants/jjkRecords/index?cardItemId=' + this.data.cardItemIdJJK,
    })
  },

  // 我的收益
  toProfits: function () {
    wx.navigateTo({
      url: '/merchant/share/holderProfits/index?isHolder=1&creatUid=' + this.data.cardInfo.CardInfo.Uid,
    })
  },


  // 已发放已核销
  toStatistics: function (e) {
    let staticsType = e.currentTarget.dataset.statictype;
    let sendCount = e.currentTarget.dataset.sendcount;
    let checkCount = e.currentTarget.dataset.checkcount;
    wx.navigateTo({
      url: '/merchant/share/statistics/index?staticsType=' + staticsType + '&sendCount=' + sendCount + '&checkCount=' + checkCount + '&creatUid=' + this.data.cardInfo.CardInfo.Uid,
    })
  },

  // 判断是否为股东
  getShareholder: function (staffUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Shareholder/GetShareholder?createUid=' + staffUid + '&shareUid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              isHolder: true
            })
          }
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  //拨打电话
  makeCallPhone: function (e) {
    let mobile = e.currentTarget.dataset.mobile;
    if (mobile) {
      wx.makePhoneCall({
        phoneNumber: mobile
      })
    }
  },

  // 获取用户所属股东
  getShareholderByUserid: function () {
    let that = this;
    let cardId = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + '/api/Shareholder/GetShareholderByClient?staffId=' + cardId + '&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.info) {
            that.setData({
              shareName: res.data.Data.info.Name
            })
          }
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  // 联盟是否有新的卡券
  isTipUser: function (staffUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/alliance/IsTipUser?createUid=' + staffUid + '&uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data > 0) {
            let allianceId = res.data.Data;
            wx.showModal({
              title: '联盟礼包更新提醒',
              content: '有新的联盟礼包可领取，立即领取？',
              success(res) {
                if (res.confirm) {
                  that.receiveAllianceCoupon(allianceId);
                } else if (res.cancel) {
                }
              }
            })
          }
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },

  // 获取联盟id并领取联盟礼包
  receiveAllianceCoupon: function (allianceId) {
    let that = this;
    let cardId = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + "/api/alliance/ReceivePackage?isRefresh=1&staffId=" + cardId + '&uid=' + app.globalData.userInfo.Uid + '&allianceId=' + allianceId,
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showToast({
            title: '领取成功',
            mask: true
          })
          that.getAllCardItems();
        } else {
          utils.showModal(res.data.Message);
        }
      },
    })
  },

  //监听用户滑动页面事件
  onPageScroll: function (e) {
    let top = parseInt(e.scrollTop);
    this.setData({
      top: top
    })
  },


  // 底部弹出层
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  showModalSend: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationDataSend: animation.export(),
      showModalStatusSend: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationDataSend: animation.export()
      })
    }.bind(this), 200)
  },

  hideModalSend: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation;
    animation.translateY(300).step()
    this.setData({
      animationDataSend: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationDataSend: animation.export(),
        showModalStatusSend: false
      })
    }.bind(this), 200)
  },


  // 生成海报
  toPoste: function () {
    var cardInfo = JSON.stringify(this.data.cardInfo);
    var userInfo = JSON.stringify(this.data.userInfo);
    var couponList = JSON.stringify(this.data.packageInfo.couponTypeList);
    wx.navigateTo({
      url: '/pages/weijieke/sharePoste/index?isHolder=1&cardinfo=' + this.encodeUnicode(cardInfo) + '&userinfo=' + this.encodeUnicode(userInfo) + '&couponList=' + this.encodeUnicode(couponList),
    })
  },

  //转赠玖玖卡海报
  toPostSend: function () {
    var that = this;
    that.hideModalSend();
    that.getWxaCodeFile();

  },

  //扫码领取玖玖卡（不限张数）
  getWxaCodeFile: function () {
    let that = this;
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    let path = 'merchant/merchants/receiveJJK/index?t=7&p=' + that.data.myCardId + '#' + that.data.cardItemIdJJK + '#' + app.globalData.userInfo.Uid + '#0#0';//参数过长生成失败
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: path,
        storeappid: app.globalData.storeAppId
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          if (res.data.Data) {
            wx.downloadFile({
              url: 'https://static.711688.net.cn/upload/user/' + res.data.Data,
              success: function (res) {
                if (res.statusCode === 200) {
                  var codeSrc = res.tempFilePath;
                  that.sharePosteCanvasJJK(codeSrc);
                } else {
                  wx.showToast({
                    title: '二维码下载失败！',
                    icon: 'none',
                    duration: 2000,
                    success: function () {
                      var codeSrc = "";
                      that.sharePosteCanvasJJK(codeSrc);
                    }
                  })
                }
              }
            })
          } else {
            var codeSrc = "";
            that.sharePosteCanvasJJK(codeSrc);
          }
        }
      },
    })
  },

  sharePosteCanvasJJK: function (codeSrc) {
    let that = this;
    that.setData({
      showpost: true
    });

    const ctx = wx.createCanvasContext('myCanvas', that);
    const query = wx.createSelectorQuery().in(this);
    query.select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var width = rect.width;
      ctx.fillStyle = '#ffffff';
      sharePost.fillRoundRect(ctx, 0, 0, width, height, 5, 'rgba(255, 255, 255, 1)');

      if (that.data.myCompany) {
        ctx.font = '18px sans-serif';
        ctx.fillStyle = 'rgba(12, 11, 9, 1)';
        ctx.setTextAlign('left');
        ctx.fillText(that.data.myCompany, width * 0.06, 28);//姓名
      }
      if (codeSrc) {
        ctx.drawImage(codeSrc, (width - width * 47 / 68) / 2, 60, width * 47 / 68, width * 47 / 68);
      }
      ctx.font = '16px sans-serif';
      ctx.fillStyle = 'rgba(12, 11, 9, 1)';
      ctx.setTextAlign('center');
      ctx.fillText('扫 码 领 取 玖 玖 卡', width / 2, 110 + width * 47 / 68);

      ctx.font = '16px sans-serif';
      ctx.fillStyle = 'rgba(137, 137, 137, 1)';
      ctx.setTextAlign('center');
      ctx.fillText('企动·玖玖客', width / 2, 160 + width * 47 / 68);//姓名

    }).exec()
    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)
  },
  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  that.closePoste();
                  if (res.confirm) { }
                },
                fail: function (res) {
                }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: '请删掉小程序再重新授权允许保存至相册',
                icon: 'none',
                duration: 2000
              })
            }
          })
        },
        fail: function (err) {
        }
      }, that);
    }, 1000);
  },
  closePoste: function () {
    this.setData({
      showpost: false
    })
  },
  
  // 转为unicode 编码
  encodeUnicode: function (str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
      res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
  },

  //绘制转发图片
  getShareImgData(couponInfo) {
    let fontSize = 27;
    let count = 9;
    let title1 = '',
      title2 = '',
      couponCondition = '',
      coupontime = '';
    if (couponInfo.useexpiretime > 0) {
      coupontime = "有效期：" + couponInfo.useexpiretime + '天';
    } else {
      coupontime = "有效期：" + couponInfo.useendtime.substr(0, 10);
    }
    if (couponInfo.money > 0) { //满减券
      title1 = "¥" + couponInfo.money;
      couponCondition = "满" + couponInfo.orderamountlower + "元使用";
    } else { //赠品券
      if (couponInfo.name != '') {
        let name = couponInfo.name
        title1 = name.substr(0, 9);
        if (name.length > 9) {
          title2 = name.substr(9, name.length);
        }
      } else {
        fontSize = 35;
        count = 7;
        if (couponInfo.extcode1 != "") {
          title2 = "买" + couponInfo.extcode1;
          title1 = "送" + couponInfo.extcode2;
        } else {
          title1 = "送" + couponInfo.extcode2;
        }
      }
    }
    this.painter('share-canvas-id', {
      bg_url: 'https://static.711688.net.cn/upload/card/source/ua_1904251534061678438.jpg', // 优惠券样式1
      title1: {
        right: 'left',
        blod: true,
        fontSize: fontSize,
        content: title1,
        x: 30,
        y: 45,
        count: count,
        color: "rgba(224, 32, 15, 1)"
      },
      title2: {
        right: 'left',
        blod: true,
        fontSize: 27,
        content: title2,
        x: 30,
        y: 85,
        count: 7,
        color: "rgba(224, 32, 15, 1)"
      },
      couponCondition: {
        right: 'left',
        blod: false,
        fontSize: 14,
        content: couponCondition,
        x: 30,
        y: 107,
        count: 10,
        color: "rgba(224, 32, 15, 1)"
      },
      coupontime: {
        right: 'left',
        blod: false,
        fontSize: 14,
        content: coupontime,
        x: 30,
        y: 140,
        count: 20,
        color: "rgba(224, 32, 15, 1)"
      },

      company: {
        right: 'left',
        blod: false,
        fontSize: 14,
        content: couponInfo.Company,
        x: 30,
        y: 175,
        count: 18,
        color: "rgba(124, 124, 124, 1)",
        len: 36
      }
    })
      .then(data => {
        this.data.shareimgpath = data;
      })
      .catch(err => { })
  },

  //宽高分别300 240(商家优惠券)
  painter: function (canasId, data) {
    var ctx = wx.createCanvasContext(canasId);
    var bg_url = data.bg_url;
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: bg_url,
        success: res => {
          if (res.statusCode === 200) {
            ctx.beginPath();
            ctx.drawImage(res.tempFilePath, 0, 0, 300, 200); // 画 背景

            // 优惠券名称
            this.setTextFill(ctx, data.title1.right, data.title1.blod, data.title1.fontSize, data.title1.content, data.title1.x, data.title1.y, data.title1.count, data.title1.color);
            this.setTextFill(ctx, data.title2.right, data.title2.blod, data.title2.fontSize, data.title2.content, data.title2.x, data.title2.y, data.title2.count, data.title2.color);

            //满多少使用
            this.setTextFill(ctx, data.couponCondition.right, data.couponCondition.blod, data.couponCondition.fontSize, data.couponCondition.content, data.couponCondition.x, data.couponCondition.y, data.couponCondition.count, data.couponCondition.color);

            // 有效期
            this.setTextFill(ctx, data.coupontime.right, data.coupontime.blod, data.coupontime.fontSize, data.coupontime.content, data.coupontime.x, data.coupontime.y, data.coupontime.count, data.coupontime.color, data.coupontime.len);

            //公司名
            this.setTextFill2(ctx, data.company.right, data.company.blod, data.company.fontSize, data.company.content, data.company.x, data.company.y, data.company.count, data.company.color);

            ctx.draw(true, () => {
              wx.canvasToTempFilePath({
                canvasId: canasId,
                success: res => {
                  resolve(res.tempFilePath)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
        }
      })
    })
  },

  /**
   * 显示文字
   * @param ctx canvas实例
   * @param align 文字对齐方式
   * @param font {Boolean} 是否加粗
   * @param fontSize   文字大小
   * @param content    文字内容
   * @param x    x坐标
   * @param y    y坐标
   * @param fontLen    文字最大长度
   * @param color    文字颜色
   * @param bytes    允许最大字节
   */
  setTextFill(...params) {
    let [ctx, align, font, fontSize, content, x, y, fontLen, color, bytes] = params;
    if (!bytes) {
      bytes = 22;
    }
    let [contentLeng, contentArray, contentRows] = sharePost.textByteLength(content.substr(0, fontLen), bytes);
    if (color) {
      ctx.fillStyle = color;
    } else {
      ctx.fillStyle = '#fff';
    }
    ctx.setTextAlign(align);
    ctx.setTextBaseline('middle');
    if (font) {
      ctx.font = 'normal bold 18px sans-serif';
    }
    ctx.setFontSize(fontSize);
    for (let m = 0; m < contentArray.length; m++) {
      ctx.fillText(contentArray[m], x, y + 15 * m);
    }
  },
  setTextFill2(...params) {
    let [ctx, align, font, fontSize, content, x, y, fontLen, color, bytes] = params;
    if (!bytes) {
      bytes = 36;
    }
    let [contentLeng, contentArray, contentRows] = sharePost.textByteLength(content.substr(0, fontLen), bytes);
    if (color) {
      ctx.fillStyle = color;
    } else {
      ctx.fillStyle = '#fff';
    }
    ctx.setTextAlign(align);
    ctx.setTextBaseline('middle');
    if (font) {
      ctx.font = 'normal bold 18px sans-serif';
    }
    ctx.setFontSize(fontSize);
    for (let m = 0; m < contentArray.length; m++) {
      ctx.fillText(contentArray[m], x, y + 15 * m);
    }
  },

  //绘制转发图片（v7.0.6版本）
  getShareImgData2() {
    this.painter2('share-canvas-id', {
      bg_url: 'https://static.711688.net.cn/images/coupon/shared3.jpg' // 红包样式
    })
      .then(data => {
        this.data.shareimgpath = data;
      })
      .catch(err => { })
  },
  painter2: function (canasId, data) {
    var ctx = wx.createCanvasContext(canasId);
    var bg_url = data.bg_url;
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: bg_url,
        success: res => {
          if (res.statusCode === 200) {
            ctx.beginPath();
            ctx.drawImage(res.tempFilePath, 0, 0, 300, 200); // 画 背景
            ctx.draw(true, () => {
              wx.canvasToTempFilePath({
                canvasId: canasId,
                success: res => {
                  resolve(res.tempFilePath)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
        }
      })
    })
  }
})